<template>
  <view v-if="tableData.length > 0">
    <u-card
      v-for="(item, index) in tableData"
      :body-style="{ padding: 0 }"
      :key="item.fileListItemId"
    >
      <template #head>
        <view class="u-flex">
          <view class="u-flex-1 u-line-1"
            >{{ index + 1 }}.
            <text
              :style="{ visibility: item.requireFile ? 'visible' : 'hidden' }"
              style="color: red; font-weight: 600"
              >*
            </text>
            <text class="font-bold">{{ item.fileName }}</text></view
          >
          <view
            ><u-tag
              v-if="item.complementFile === 1 && props.taskInfo.taskType === 3"
              :text="'可后补'"
              type="info"
            ></u-tag
          ></view>
        </view>
        <view v-if="item.fileDesc" class="u-tips-color">
          {{ item.fileDesc }}</view
        >
      </template>
      <template #body>
        <u-cell-group v-if="item.fileDetailList && item.fileDetailList.length">
          <template
            v-for="(el, index) in item.fileDetailList"
            :key="el.platformFileId"
          >
            <u-cell-item
              :arrow="false"
              :border-bottom="
                hasOtherBtn(el) || el.viewSignStatus === 1 ? false : true
              "
              @click="showActionSheet(el, item)"
            >
              <template #title>
                <text class="u-content-color">{{ el.fileName }}</text>
              </template>
              <template v-if="!isUpload" #right-icon>
                <view>
                  <u-button
                    size="mini"
                    type="primary"
                    :loading="el.loading"
                    @click="preview(el)"
                    >预览</u-button
                  >
                </view>
              </template>
              <template #label>
                <u-tag
                  v-if="el.version"
                  size="mini"
                  borderColor="transparent"
                  :text="el.version || '无'"
                  type="info"
                ></u-tag>
                <u-tag
                  v-if="el.versionDate"
                  size="mini"
                  borderColor="transparent"
                  class="u-m-l-10"
                  :text="el.versionDate || '无'"
                  type="info"
                ></u-tag>
                <u-tag
                  size="mini"
                  borderColor="transparent"
                  v-if="
                    item.complementFile === 1 &&
                    props.taskInfo.taskType === 3 &&
                    el.noAllowFlag === false
                  "
                  class="u-m-l-10"
                  text="后补"
                  type="info"
                ></u-tag>
              </template>
            </u-cell-item>
            <!-- 判断有撤回签署||签署||查看签署||个人签名才有cell -->
            <u-cell-item
              :arrow="false"
              v-if="hasOtherBtn(el) || el.viewSignStatus === 1"
            >
              <view class="u-flex u-row-between fileList-sign-btn">
                <u-button
                  v-if="el.viewSignStatus === 1"
                  size="medium"
                  type="primary"
                  :loading="el.viewSignLoading"
                  @click="viewsignFile(el)"
                  :style="{
                    flex: hasOtherBtn(el) ? 0 : 1,
                  }"
                  :class="[hasOtherBtn(el) ? 'review-sign' : '']"
                  shape="circle"
                  plain
                  >查看签署</u-button
                >
                <u-button
                  v-if="el.userSignStatus === 0"
                  size="medium"
                  type="primary"
                  :loading="el.signLoading"
                  @click="signFile(el)"
                  class="sign-btn"
                  shape="circle"
                  >签名</u-button
                >
                <u-button
                  v-if="el.userSignStatus === 1"
                  size="medium"
                  :loading="el.recallLoading"
                  @click="recallSignFile(el)"
                  class="sign-plain-btn"
                  shape="circle"
                  >撤回签署</u-button
                >
                <u-button
                  v-if="el.orgSignStatus === 0"
                  size="medium"
                  :loading="el.signOrgLoading"
                  @click="signOrgFile(el)"
                  class="sign-btn"
                  shape="circle"
                  >签章</u-button
                >
              </view>
            </u-cell-item>
          </template>
        </u-cell-group>
        <u-empty v-else mode="data"></u-empty>
        <template v-if="isUpload">
          <view class="u-p-20 margin-x-auto file-list-button">
            <u-button
              type="primary"
              :disabled="
                !(
                  (item.fileAmount > 0 &&
                    (item.fileDetailList || []).length < item.fileAmount) ||
                  item.fileAmount === 0
                )
              "
              plain
              @click.stop="uploadFileClick(item)"
              >上传文件</u-button
            >
          </view>
        </template>
      </template>
    </u-card>
  </view>
  <u-empty v-else mode="data"></u-empty>

  <!--上传文件-->
  <uploadFile ref="refUploadFile" @submit="chooseFile"></uploadFile>

  <u-action-sheet
    :list="list"
    v-model="actionSheetShow"
    :cancel-btn="true"
    :safe-area-inset-bottom="true"
    @click="click"
  ></u-action-sheet>
</template>
<script lang="ts" setup>
import { getTaskFileDetailList } from '@/api/modules/project';
import { getfileDetailList } from '@/api/modules/finance';
import { getUploadUrl } from '@/utils/env';
import {
  sendSignFile,
  viewSign,
  revokeSign,
  orgSignFile,
} from '@/api/modules/signFile';
import uploadFile from './components/uploadFile.vue';
import { useUserStore } from '@/stores/user';

const userStore = useUserStore();
const orgInfo = userStore.getOrgInfo;

const props = defineProps<{
  taskInfo: any;
  isUpload?: boolean;
}>();
const tableData = ref<any>([]);
const { taskInfo, isUpload } = props;
const refUploadFile = ref();

const list = [
  {
    text: '预览',
  },
  {
    text: '删除',
  },
];

const currItem = ref();
const uploadFileClick = (item: any) => {
  currItem.value = item;
  refUploadFile.value.show(item.requireVersion, item.fileFormat);
};
// 分解文件
function splitFile(fileName: string) {
  const index = fileName.lastIndexOf('.') + 1;
  return {
    fileName: index < 1 ? fileName : fileName.substring(0, index - 1),
    fileType: fileName.substring(index),
  };
}
const chooseFile = (res: any) => {
  const filefj = splitFile(res.fileList[0].name);
  if (!currItem.value.fileDetailList) {
    currItem.value.fileDetailList = [];
  }
  currItem.value.fileDetailList.push({
    projectTaskFileId: '',
    platformFileId: res.fileList[0].uid,
    fileName: res.fileList[0].name,
    extension: filefj.fileType,
    fileSize: res.fileList[0].size,
    version: res.version,
    versionDate: res.versionDate,
  });
};

// 校验方法
function check() {
  tableData.value.forEach((item: any) => {
    // 如果是立项文件并且可候补，直接进入下次循环
    console.log(item);
    if (
      (item.complementFile !== 1 && props.taskInfo.taskType === 3) ||
      props.taskInfo.taskType !== 3
    ) {
      if (!item.fileDetailList) {
        item.fileDetailList = [];
      }
      if (item.requireFile) {
        if (item.fileDetailList.length === 0) {
          throw new Error(`《${item.fileName}》 请上传文件`);
        }
        if (item.fileDetailList.length < item.fileAmount) {
          throw new Error(
            `《${item.fileName}》需要上传文件数为【${item.fileAmount}】, 已上传文件数量【${item.fileDetailList.length}】, 请检查`
          );
        }
      } else if (
        item.fileDetailList.length > 0 &&
        item.fileDetailList.length < item.fileAmount
      ) {
        throw new Error(
          `《${item.fileName}》需要上传文件数为【${item.fileAmount}】, 已上传文件数量【${item.fileDetailList.length}】, 请检查`
        );
      }
    }
    if (item.requireVersion) {
      for (let i = 0; i < item.fileDetailList.length; i++) {
        const file = item.fileDetailList[i];
        if (!file.version) {
          throw new Error(`《${item.fileName}-${file.fileName}》请填写版本号`);
        }
        if (!file.versionDate) {
          throw new Error(`【${item.fileName}文件版本日期不能为空`);
        }
      }
    }
  });
}

function reloadData() {
  if (taskInfo.isCommonDetail) {
    getfileDetailList({ taskId: taskInfo.taskId }).then((res) => {
      tableData.value = res || [];
    });
  } else {
    getTaskFileDetailList({ taskId: taskInfo.taskId }).then((res) => {
      tableData.value = res || [];
    });
  }
}

reloadData();
// 预览
const preview = (item: any) => {
  const timestamp = new Date().getTime();
  item.loading = true;
  uni.downloadFile({
    url: `${getUploadUrl()}/Rest/doc/file/filePreview?timestamp=${timestamp}&orgId=${
      orgInfo.orgId
    }&docId=${item.platformFileId}`,
    success: function (res: any) {
      console.log(res);
      item.loading = false;
      const FILE_NAME_REGX: any = /.*filename=([\w%-_.]+(.\w+)?)/;
      const contentDisposition = res.header['Content-disposition'];
      const fileName = FILE_NAME_REGX.test(contentDisposition)
        ? FILE_NAME_REGX.exec(contentDisposition)[1]
        : 'fileName.txt';
      const type = fileName.split('.');
      var filePath = res.tempFilePath;
      const imgTypeArr = [
        'bmp',
        'jpg',
        'png',
        'tif',
        'gif',
        'pcx',
        'tga',
        'exif',
        'fpx',
        'svg',
        'psd',
        'cdr',
        'pcd',
        'dxf',
        'ufo',
        'eps',
        'ai',
        'raw',
        'WMF',
        'webp',
        'avif',
        'apng',
      ];
      if (
        ['doc', 'xls', 'ppt', 'pdf', 'docx', 'xlsx', 'pptx', 'txt'].includes(
          type[type.length - 1].toLowerCase()
        )
      ) {
        // uni.openDocument({
        //   filePath: filePath,
        //   fileType: type[type.length - 1].toLowerCase(),
        //   // showMenu: true,
        //   success: function (res) {
        //     console.log('打开文档成功');
        //   },
        // });
        // } else if (type[type.length - 1].toLowerCase() === 'txt') {
        const href =
          'https://ow365.cn/?i=17462&ssl=1&furl=' +
          `${getUploadUrl()}/Rest/doc/file/filePreview?timestamp=${timestamp}&orgId=${
            orgInfo.orgId
          }&docId=${item.platformFileId}`;
        uni.setStorageSync('signHref', href);
        (uni as any).$Router.push({
          name: 'autograph',
        });
      } else if (imgTypeArr.includes(type[type.length - 1].toLowerCase())) {
        uni.previewImage({
          urls: [res.tempFilePath],
        });
      }
    },
    fail: function (e) {
      uni.showModal({
        title: '温馨提示',
        content: '文件预览失败',
        confirmText: '确认',
        showCancel: false,
      });
      item.loading = false;
    },
  });
};
const hasOtherBtn = (el: any) => {
  return (
    el.userSignStatus === 0 || el.userSignStatus === 1 || el.orgSignStatus === 0
  );
};
const signFile = async (file: any) => {
  file.signLoading = true;
  try {
    let res: any = await sendSignFile({
      platformFileId: file.platformFileId,
      businessId: taskInfo.taskId,
      businessType: taskInfo.taskType,
      clientType: 'H5',
      redirectUrl: 'wechat://back',
    });

    uni.navigateTo({
      url: '/pages/my/sign/webview/index?url=' + encodeURIComponent(res),
    });
    file.signLoading = false;
  } catch {
    file.signLoading = false;
  }
};
const signOrgFile = async (file: any) => {
  file.signOrgLoading = true;
  try {
    let res: any = await orgSignFile({
      platformFileId: file.platformFileId,
      businessId: taskInfo.taskId,
      businessType: taskInfo.taskType,
      clientType: 'H5',
      redirectUrl: 'wechat://back',
    });
    file.signOrgLoading = false;
    uni.navigateTo({
      url: '/pages/my/sign/webview/index?url=' + encodeURIComponent(res),
    });
  } catch {
    file.signOrgLoading = false;
  }
};
const viewsignFile = async (file: any) => {
  file.viewSignLoading = true;
  try {
    let res: any = await viewSign({
      platformFileId: file.platformFileId,
    });
    file.viewSignLoading = false;
    uni.navigateTo({
      url: '/pages/my/sign/webview/index?url=' + encodeURIComponent(res),
    });
  } catch {
    file.viewSignLoading = false;
  }
};
const recallSignFile = async (file: any) => {
  uni.showModal({
    title: '提示',
    content:
      '执行撤回签署操作，会导致所有人都需要重新签署，请确认是否撤回签署？',
    confirmText: '确认',
    success: async (res) => {
      if (res.confirm) {
        file.recallLoading = true;
        try {
          await revokeSign({
            platformFileId: file.platformFileId,
            businessId: taskInfo.taskId,
            businessType: taskInfo.taskType,
            clientType: 'H5',
          });
          uni.showToast({
            title: '操作成功',
            icon: 'none',
            duration: 2000,
          });
          reloadData();
          file.recallLoading = false;
        } catch {
          file.recallLoading = false;
        }
      }
    },
  });
};

const getData = () => {
  return tableData.value;
};

const removeItem = (item: any) => {
  const index = currFileTypeItem.value.fileDetailList.findIndex(
    (el: any) => el.platformFileId === item.platformFileId
  );
  if (index > -1) {
    currFileTypeItem.value.fileDetailList.splice(index, 1);
  }
};
const click = (index: number) => {
  if (index === 0) {
    // 预览
    preview(currFileItem.value);
  } else {
    // 删除
    removeItem(currFileItem.value);
  }
};

const currFileItem = ref();
const currFileTypeItem = ref();
const actionSheetShow = ref(false);
const showActionSheet = (item: any, typeItem: any) => {
  if (!isUpload) {
    return;
  }
  currFileItem.value = item;
  currFileTypeItem.value = typeItem;
  actionSheetShow.value = true;
};

defineExpose({
  check,
  getData,
  reloadData,
});
</script>
<style lang="scss">
::v-deep .u-cell {
  padding: 0 !important;
}

.w-40 {
  width: 40%;
}
.margin-x-auto {
  margin: 0 auto;
}

.file-list-button {
  :deep(.u-btn--primary--disabled) {
    color: #ccc !important;
  }
}
</style>
